<template>
  <div class="users">
    <!-- 面包屑导航部分 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索区、 -->
    <div style="margin-top: 15px;">
      <el-input
        placeholder="请输入内容"
        v-model="query"
        class="input-with-select"
        @keyup.enter.native="search"
        style="width:300px;margin-right:15px"
      >
        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
      </el-input>
      <el-button type="success" @click="addDialogFormVisible=true">添加用户</el-button>
    </div>
    <!-- 表格区域部分 -->
    <el-table :data="userList" border style="width: 100%">
      <!-- 这里的：data是表格的数据源 我们的数据源是用户列表 -->
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="username" label="姓名" width="120"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="120"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <!-- 添加自定义模板 -->
      <el-table-column label="修改状态">
        <template slot-scope="scope">
          <el-switch
            @change="changeUserState(scope.row.id,scope.row.mg_state)"
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top">
            <el-button type="primary" icon="el-icon-edit" @click="showEditUserData(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
            <el-button type="primary" icon="el-icon-share" @click="showGrantDialog(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="primary" icon="el-icon-delete" @click="deletUserById(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible">
      <el-form :model="addForm" :label-width="'80px'" :rules="rules" ref="addForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" auto-complete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" auto-complete="off" type="password" clearable></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色分配对话框 -->
    <el-dialog title="角色分配" :visible.sync="grantdialogFormVisible">
      <el-form :model="grantForm" :label-width="'120px'">
        <el-form-item label="用户名">
          <el-input v-model="grantForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="grantForm.rid" clearable placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- //编辑对话框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm"  :label-width="'120px'" :rules="rules" ref="editForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off" disabled=""></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserSubmitData">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 引入接口方法
import {
  getUserList,
  addUser,
  deletUser,
  grantUserRole,
  updateUserState,
  editUser
} from '../src/api/user_api.js'
import { getAllRoleList } from '@/api/role_api.js'
// import { login } from 'util'
// export default {};
export default {
  data () {
    return {
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      value4: '',
      roleList: [],
      grantForm: {
        username: '',
        id: '',
        rid: ''
      },
      // 编辑用户对话框
      editDialogFormVisible: false,
      // 定义角色对话框
      grantdialogFormVisible: false,
      // 定义添加对话框的显示或隐藏
      addDialogFormVisible: false,
      // 添加用户对话框数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      total: 0,
      // 用户搜索关键字在后台拿到
      query: '',
      // 当前页码
      pagenum: 1,
      // 每页显示的记录数
      pagesize: 1,
      value2: true,
      userList: [],
      // 添加用户规则
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6-16位数字', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /\w+[@]\w+[.]\w{2,3}/,
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          {
            pattern: /^1[345678]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted () {
    // 钩子函数进行数据传值、
    // 调用int方法
    this.int()
    // 拿到所有的角色数据
    console.log(getAllRoleList, getUserList, 'getAllRoleList')
    getAllRoleList().then(res => {
      console.log(res, '获取权限列表')
    })
    getAllRoleList().then(res => {
      // console.log(res)
      if (res.data.meta.status === 200) {
        this.roleList = res.data.data
        console.log(this.roleList, 'opyions')
      }
    })
  },
  methods: {
    // 编辑用户数据进行提交
    editUserSubmitData () {
      // 通过添加ref拿到对应editform的数据
      this.$refs.editForm.validate(valid => {
        if (valid) {
        // 如果是编辑成功的话就调用接口方法让数据进行更新
          editUser(this.editForm)
            .then(res => {
              // console.log(res)
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: res.data.meta.msg
                })
                this.editDialogFormVisible = false
                this.int()
              } else {
                this.$message({
                  type: 'warning',
                  message: '数据有误'
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
    },
    // 显示编辑用户对话框
    showEditUserData (row) {
      // 把旧数据展示
      this.editForm.username = row.username
      this.editForm.id = row.id
      this.editForm.email = row.email
      this.editForm.mobile = row.mobile
      this.editDialogFormVisible = true
    },
    // 修改用户状态
    changeUserState (id, type) {
      updateUserState(id, type).then(res => {
        console.log(res)
        if (res.data.meta.status === 200) {
          this.$message({
            type: 'success',
            message: res.data.meta.msg
          })
        }
      })
    },
    // 点击确定分配角色成功
    grantRoleSubmit () {
      // 判断是否选择了角色
      if (!this.grantForm.rid) {
        this.$message({
          type: 'warning',
          message: '请先选择角色'
        })
        return false
      }

      grantUserRole(this.grantForm.id, this.grantForm.rid).then(res => {
        console.log(res)
        if (res.data.meta.status === 200) {
          this.$message({
            type: 'success',
            message: res.data.meta.msg
          })
          this.grantdialogFormVisible = false
        }
      })
    },
    // 分配角色
    showGrantDialog (row) {
      console.log(row, 'gytytuf')
      this.grantdialogFormVisible = true
      this.grantForm.username = row.username
      this.grantForm.id = row.id
      this.grantForm.rid = row.rid

      // 获取分配角色
      // grantUserRole(this.grantForm.id, this.grantForm.rid).then(res => {
      //   console.log(res)
      //   if (res.data.meta.status === 200) {
      //     this.$message({
      //       type: 'success',
      //       message: res.data.meta.msg
      //     })
      //     this.grantdialogFormVisible = false
      //   }
      // })
    },

    // 根据id删除用户数据的操作
    deletUserById (id) {
      // 点击删除弹出删除确认框
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 调用接口方法删除对应的id
          deletUser(id)
            .then(res => {
              // console.log(res)
              if (res.data.meta.status === 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                // 这里我们还需要判断如果我们删除的数据当前页没有数据了就需要跳到上一页，有数据就不需要跳
                this.pagenum =
                  Math.ceil((this.total - 1) / this.pagesize) < this.pagenum
                    ? --this.pagenum
                    : this.pagenum
                // 重新加载页面
                this.int()
              }
            })
            .catch(err1 => {
              // console.log(err)
              this.$message({
                type: 'error',
                message: '删除失败!'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击确定获取数据
    addUser () {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          // 如果有效调用接口方法，传数据
          addUser(this.addForm)
            .then(res => {
              // console.log(res)
              if (res.data.meta.status === 201) {
                this.addDialogFormVisible = false
                this.$refs.addForm.resetFields()
                // this.int()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.meta.msg
                })
              }
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          return false
        }
      })
    },
    showAddUserDialog () {},
    // 封装方法
    search () {
      this.pagenum = 1
      this.int()
    },
    // 这里把获取的数据封装
    int () {
      getUserList({
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize
      })
        .then(res => {
          // console.log(res)
          // 获取用户数据
          this.userList = res.data.data.users
          // 获取总记录数
          this.total = res.data.data.total
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      // 再次拉起总共有多少条
      this.pagesize = val
      this.int()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      // 因为我们每次切换页码数的时候都会改变当前页，
      this.pagenum = val
      this.int()
    }
  }
}
</script>
<style lang="less" scoped>
</style>
